import optparse
import sys
import base64
import hashlib
from cryptography.fernet import Fernet
from PIL import Image
import stepic

def encrypt(mess, img):    
    mess = mess.encode('utf-8')
    encrypt = cipher.encrypt(mess)

    img = Image.open(img)
    resalt = stepic.encode(img, encrypt)
    resalt.save('resalt.png', 'PNG')	 
    print('\nOK')   

def decrypt(img):
    img = Image.open(img)
    mess = stepic.decode(img)
    
    mess = mess.encode('utf-8')
    decrypted_text = cipher.decrypt(mess)
    print('\n' + decrypted_text.decode('utf-8'))
    
pars = optparse.OptionParser()
pars.add_option('-e', dest='encrypt', help='шифровать -e /home/user/img.img -k key')
pars.add_option('-d', dest='decrypt', help='расшифровать -d /home/user/img.img -k key')
pars.add_option('-f', dest='file', help='текстоввый файл')
pars.add_option('-l', dest='line', help='строка')
pars.add_option('-k', dest='key', help='ключ шифрования')

(opt, arg) = pars.parse_args()

if not opt.key:
    print('Укажи ключ шифрования')
    sys.exit()
else:
    hash_key = hashlib.md5(opt.key.encode('utf-8'))
    res_hash_key = hash_key.hexdigest() 
    key = base64.b64encode(bytes(res_hash_key, 'utf-8'))
    cipher = Fernet(key)

    if opt.encrypt:
        img = opt.encrypt
        mess = ''

        if opt.file:
            with open(opt.file, 'r') as file:
                mess = file.read()

        elif opt.line:
            mess = opt.line


        encrypt(mess, img)

    elif opt.decrypt:
        img = opt.decrypt
        decrypt(img)
